import 'dart:async';

import 'package:enjoy_plus_hm/utils/eventbus.dart';
import 'package:enjoy_plus_hm/utils/toast.dart';
import 'package:enjoy_plus_hm/utils/token.dart';
import 'package:flutter/material.dart';

import '../../utils/http.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  int _count = 10;
  bool _isCountDown = false;
  Timer? _timer;
  void _startCountDown() {
    //判断是否在倒计时
    if (_isCountDown) {
      return;
    }
    _isCountDown = true;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_count > 0) {
          _count--;
        } else {
          _isCountDown = false;
          _count = 10;
          _timer?.cancel();
        }
      });
    });
  }

  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();
  // 获取验证码
  void getCode() async {
    // 获取输入的手机号
    String phone = _phoneController.text;
    // 判断是否有手机号
    if (phone.isEmpty) {
      return ToastUtil.showError('请输入手机号');
    }
    RegExp reg = RegExp(r'^1[0-9]\d{9}$');
    if (!reg.hasMatch(phone)) {
      return ToastUtil.showError('请输入正确的手机号');
    }
    // 调用接口获取验证码
    var res = await http.get(
      '/code',
      params: {'mobile': _phoneController.text},
    );
    if (res['code'] != 10000) {
      return ToastUtil.showError('获取验证码失败');
    }
    setState(() {
      _codeController.text = res['data']['code'];
    });
  }

  // 登录
  void goLogin() async {
    if (_phoneController.text.isEmpty || _codeController.text.isEmpty) {
      return ToastUtil.showError('请输入手机号和验证码');
    }
    RegExp reg = RegExp(r'^1[0-9]\d{9}$');
    if (!reg.hasMatch(_phoneController.text)) {
      return ToastUtil.showError('请输入正确的手机号');
    }
    RegExp reg1 = RegExp(r'\d{6}$');
    if (!reg1.hasMatch(_codeController.text)) {
      return ToastUtil.showError('请输入正确的验证码');
    }
    // 调登录接口
    var res = await http.post(
      '/login',
      data: {'mobile': _phoneController.text, 'code': _codeController.text},
    );
    if (res['code'] != 10000) return ToastUtil.showError('登录失败');
    // 保存token
    await TokenManager().saveToken(res['data']['token']);
    // 清理定时器
    _timer?.cancel();
    eventBus.fire(refreshMineEvent());
    // 返回上一页
    Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('登录'), centerTitle: true),
      body: Container(
        padding: EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '登录',
              style: TextStyle(fontSize: 26, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 30),
            Text('加入享+,让生活更轻松', style: TextStyle(fontSize: 14)),
            const SizedBox(height: 30),
            Row(
              // mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: TextField(
                    controller: _phoneController,
                    keyboardType: TextInputType.phone,
                    maxLength: 11,
                    decoration: InputDecoration(labelText: '手机号'),
                  ),
                ),
                const SizedBox(height: 10),
                TextButton(
                  onPressed: () {
                    getCode();
                  },
                  child:
                      _isCountDown
                          ? Text(
                            '$_count s后重新获取验证码',
                            style: TextStyle(
                              fontSize: 12,
                              color: const Color.fromARGB(255, 113, 113, 114),
                            ),
                          )
                          : Text(
                            '获取验证码',
                            style: TextStyle(fontSize: 12, color: Colors.blue),
                          ),
                ),
              ],
            ),
            const SizedBox(height: 10),
            TextField(
              controller: _codeController,
              keyboardType: TextInputType.phone,
              maxLength: 6,
              decoration: InputDecoration(labelText: '验证码'),
            ),
            Text(
              '未注册手机号经验证后将自动登录',
              style: TextStyle(fontSize: 12, color: Colors.grey),
            ),
            const SizedBox(height: 30),
            ElevatedButton(
              onPressed: () {
                goLogin();
                // TokenManager().saveToken('1111111');
                // Navigator.of(context).pushReplacementNamed('/');
              },
              child: Text(
                '登录',
                style: TextStyle(fontSize: 14, color: Colors.white),
              ),
              style: ElevatedButton.styleFrom(
                minimumSize: Size(double.infinity, 48),
                backgroundColor: Color.fromARGB(255, 133, 179, 199),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
